package com.i2works.smartluolong.web.service.flow;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.i2works.smartluolong.utils.base.DateConstant;
import com.xiaoleilu.hutool.util.CollectionUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/6/5 16:43
 */

public class CalendarTest {

    //    // 默认时间格式
//    private static final DateTimeFormatter DEFAULT_DATETIME_FORMATTER = TimeFormat.SHORT_DATE_PATTERN_LINE.formatter;
//
    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat(DateConstant.YYYY_MM_DD);
        Date startTime = format.parse("2018-06-12");
        Date endTime = format.parse("2018-06-16");
        System.out.println(calLeaveDays(startTime, endTime));
    }

    public static double calLeaveDays(Date startTime, Date endTime) {
        double leaveDays = 0;
        //从startTime开始循环，若该日期不是节假日或者不是周六日则请假天数+1
        Date flag = startTime;//设置循环开始日期
        Calendar cal = Calendar.getInstance();
        //从数据库得到节假日的起始日期和终止日期
        List<JSONObject> dateList = getDate();

        //用于格式化日期
        int week;
        outer:
        while (flag.compareTo(endTime) != 1) {
            cal.setTime(flag);
            //判断是否为周六日
            week = cal.get(Calendar.DAY_OF_WEEK) - 1;
            if (week == 0 || week == 6) {//0为周日，6为周六
                //跳出循环进入下一个日期
                cal.add(Calendar.DAY_OF_MONTH, +1);
                flag = cal.getTime();
            } else {
                //判断是否为节假日
                if (CollectionUtil.isNotEmpty(dateList)) {
                    for (JSONObject json : dateList) {
                        Date startDay = json.getDate("startDay");
                        Date endDay = json.getDate("endDay");
                        if (flag.compareTo(startDay) > -1 && flag.compareTo(endDay) < 1) {
                            //跳出循环进入下一个日期
                            cal.add(Calendar.DAY_OF_MONTH, -1);
                            leaveDays++;
                            flag = cal.getTime();
                            continue outer;
                        }
                    }
                }
            }


        }
        return leaveDays;
    }

    private static List<JSONObject> getDate() {
        List<JSONObject> list = Lists.newArrayList();
        for (int i = 0; i < 12; i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("startDay", "2017-" + String.format("%02d", (i + 1)) + "-13");
            jsonObject.put("endDay", "2018-" + String.format("%02d", (i + 1)) + "-14");
            list.add(jsonObject);
        }
        return list;
    }


}
